package be.gnx.fogo.application.dao;

import java.util.Hashtable;
import java.util.List;

import org.hibernate.Query;

import be.gnx.fogo.application.model.Person;
import be.gnx.fogo.application.util.HibernateUtil;

public class PersonDao extends ObjectDao<Person, Long> {

  public PersonDao() {
    super(Person.class, "id");
  }

  public Hashtable<Long, String> findByNames(String searchString) {
    Hashtable<Long, String> hashtable = new Hashtable<Long, String>();
    if ((searchString != null) && (searchString.length() > 0)) {
      String[] searchTerms = searchString.split(" ");
      StringBuffer hql = new StringBuffer("select id, alternativeName.value, surname.value from Person as person where ");
      for (int index = 0; index < searchTerms.length; index++) {
        if (index > 0) {
          hql.append(" and (");
        }
        hql.append("lower(person.alternativeName.value) like '%"
            + searchTerms[index].toLowerCase() + "%'");
        hql.append(" or lower(person.surname.value) like '%"
            + searchTerms[index].toLowerCase() + "%'");
        if (index > 0) {
          hql.append(")");
        }
      }
      Query query = HibernateUtil.createQuery(hql.toString());
      List<Object[]> persons = query.list();
      for (Object[] person : persons) {
        String name = person[2] + " " + person[1];
        hashtable.put(((Long)person[0]), name);
      }
    }
    return hashtable;
  }

}
